package cn.quicklydoit.resource;


import cn.quicklydoit.entity.LocalFile;
import cn.quicklydoit.entity.LocalFileBody;
import cn.quicklydoit.service.LocalFileService;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.http.entity.mime.content.FileBody;
import org.eclipse.microprofile.openapi.annotations.Operation;
import org.eclipse.microprofile.openapi.annotations.tags.Tag;
import org.jboss.logging.Logger;
import org.jboss.resteasy.plugins.providers.multipart.OutputPart;
import org.jboss.resteasy.reactive.MultipartForm;
import org.jboss.resteasy.reactive.common.providers.serialisers.FileBodyHandler;

import javax.inject.Inject;
import javax.ws.rs.*;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Consumes({MediaType.APPLICATION_OCTET_STREAM,MediaType.TEXT_PLAIN,MediaType.APPLICATION_JSON})
@Produces({MediaType.APPLICATION_OCTET_STREAM,MediaType.TEXT_PLAIN,MediaType.APPLICATION_JSON})
@Path("/file")
@Tag(name = "LocalFileResource",description="文件上传接口列表")
public class LocalFileResource {

    private static final Logger LOG = Logger.getLogger(LocalFileResource.class);


    @Inject
    LocalFileService localFileService;

    @POST
    @Path("/upload")
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.MULTIPART_FORM_DATA)
    @Operation(summary = "上传文件",description = "测试文件上传接口")
    public LocalFile upload(@MultipartForm LocalFileBody uploadEntity) throws IOException {

        InputStream i = uploadEntity.getFile().getBody(InputStream.class, null);
        String[] contentDisposition = uploadEntity.getFile().getHeaders().getFirst("Content-Disposition").split(";");
        String fileName = "";
        for (String filename : contentDisposition) {
            if ((filename.trim().startsWith("filename"))) {
                String[] name = filename.split("=");
                fileName = name[1].trim().replaceAll("\"", "");
            }
        }

        LocalFile localFile=new LocalFile();
        System.out.println(uploadEntity);
        return localFileService.add(localFile);
    }


    @GET
    @Path("/download")
    @Produces(MediaType.APPLICATION_OCTET_STREAM)
    public Response download(@QueryParam("fileName") String fileName) {
        String filePath = "E:\\工作相关\\" + fileName;
        File file = FileUtils.getFile(filePath);
        //对输出的文件名进行编码，防止下载的中文文件名乱码
        String encodFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8);
        return Response.ok(file)
                .header("content-disposition", "attachment; filename=\"" + encodFileName + "\"")
                .header("Content-Length", file.length())
                .build();
    }
}
